package Thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 自己实现线程池的简单代码
 */

class MyThreadPool{
    //初始的时候创建一个阻塞队列,分配1000空间
    //这里的 Runnable 代表可以被线程执行的任务
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    //此处 n 表示创建的线程数
    public MyThreadPool(int n){
        //先创建出 n 个线程
        for(int i = 0;i < n;i ++){
            Thread t = new Thread(()->{
                //循环的从队列中取出任务
                while (true) {
                    Runnable runnable = null;
                    try {
                        runnable = queue.take();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    runnable.run();
                }
            });
            t.start();
        }
    }


//添加任务
public void submit(Runnable runnable){
    try {
        queue.put(runnable);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
}
public class Demo34 {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(4);
        for(int i = 0;i < 1000;i ++){
            int id = 1;
                pool.submit(()->{
                    System.out.println("执行任务" + id + "," + Thread.currentThread().getName());
                });
        }
    }

}
